package com.wsh.controller.sys;

import com.wsh.annotation.AnonymousAccess;
import com.wsh.entity.sys.FileEntity;
import com.wsh.sys.FileService;
import com.wsh.utils.JsonResult;
import com.wsh.vo.sys.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author 王思涵
 * @Date 2019/8/3
 * @Version 1.0
 * @Desciption
 **/
@Slf4j
@RestController
@RequestMapping("/sys/file")
@Api(tags = "系统：附件管理")
public class FileUploadController {

    /**
     * 文件管理业务
     */
    @Autowired
    private FileService fileService;

    @Value("${filePath}")
    private String disPath;

    /**
     * 附件上传
     *
     * @param fileVo
     * @return
     */
    @ApiOperation("文件上传")
    @PreAuthorize("@el.check('file:upload')")
    @PostMapping("/upload")
    public Object upload(FileVo fileVo) throws Exception {
        fileVo.setDiskPath(this.disPath);
        // 富文本编辑器
        if (fileVo.getEditorType() == 1) {
            Map resultEditor = new HashMap();
            resultEditor.put("errno", 0);
            resultEditor.put("data", fileService.saveFileInfo(fileVo).get("fileName").toString().split(","));
            return resultEditor;
        }
        // 附件上传
        return JsonResult.success(fileService.saveFileInfo(fileVo));
    }

    @ApiOperation("附件下载")
    @AnonymousAccess
    @PostMapping("/downFile")
    public void downFile(String path, String fileName, Boolean zip, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        File file = new File(this.disPath + File.separator + path);
        try (FileInputStream fis = new FileInputStream(file);) {
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            log.error("FileUploadController ==>> downFile 下载异常 Exception={}", e.getMessage());
        } finally {
            if (zip != null && zip) {
                file.delete();
            }
        }
    }

    // 检查之前可对是否能下载附件进行处理 （附件下载端口未不拦截）
    @ApiOperation("检查附件是否存在")
    @GetMapping("/checkFileExist")
    @PreAuthorize("@el.check('file:downFile')")
    public Object checkFileExist(@RequestParam String fileId) {
        FileEntity fileEntity = fileService.getById(fileId);
        if (fileEntity != null) {
            String diskPath = fileEntity.getDiskPath();
            File file = new File(diskPath);
            if (file.exists()) {
                Map<String, Object> maps = new HashMap<>();
                maps.put("path", fileEntity.getFileName());
                maps.put("fileName", fileEntity.getRealName());
                return JsonResult.success(maps);
            }
        }
        return JsonResult.fail("当前下载文件不存在，请联系管理员");
    }
}
